package com.xiaochun.hxhj;

import android.app.ActionBar;
import android.graphics.Color;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Layout;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.AbsoluteSizeSpan;
import android.text.style.ForegroundColorSpan;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.SeekBar;
import android.widget.TextView;

import com.myview.CustomProgressDialog;
import com.myview.MarqueTextView;
import com.myview.MySeekBar;
import com.myview.RegionNumberEditText;
import com.util.DensityUtil;
import com.util.MyLog;
import com.util.RequestManager;
import com.util.ToastUtils;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 速读view作为绿条背景
 */
public class FreeSpeedActivity3 extends BaseActivity {


    private TextView tv_text;
    private int screenwidth;
    private int screenheight;
    private TextView view_line_bg;
    private Handler handlerdelay;
    private ScrollView scrollView;
    private long contentlength = 0;
    private String contentobj;
    private int lineHeight = 33;
    private int addcount = 1;
    private String bookid = "";
    private String id = "";
    private String bookname = "";
    private String bookauthor = "";
    private String file = "";
    private JSONArray minute_num;
    private CustomProgressDialog customProgressDialog;
    private MarqueTextView tv_titlebook;
    private LinearLayout ll_rebackf;
    private MySeekBar seek_progress;
    private int changeprogress = 0;
    private TextView tv_progress_tv;
    private PopupWindow mPopupWindowtime;
    private ImageView tv_set;
    private int num1 = 300;
    private int timeting = 1000;
    private ImageView img_start;
    private boolean islongscreen = false;
    private PopupWindow mPopupResultWindow;
    public int readline = 1;
    private String locationkey = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        customProgressDialog = new CustomProgressDialog(context, "", R.style.CommProgressDialog);
        WindowManager.LayoutParams params = customProgressDialog.getWindow().getAttributes();
        params.alpha = 0.7f;//取值为0-1之间  0是全透明，1是不透明
        params.dimAmount = 0f;   //取值为0-1之间  1是全黑
        customProgressDialog.getWindow().setAttributes(params);
        customProgressDialog.show();
    }

    @Override
    protected void initListener() {
        tv_set.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                img_start.setImageResource(R.mipmap.icon_start);
                img_start.setTag(0);
                handlerdelay.removeCallbacksAndMessages(null);
//                popbysettime();
                popbygrade(tv_set);
            }
        });
        ll_rebackf.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                finish();
            }
        });
        img_start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                int tag = (int) img_start.getTag();
                if (tag == 0){
                    img_start.setImageResource(R.mipmap.icon_stop);
                    img_start.setTag(1);
                    //字每行
                    String linenumcount = getUserInfo("linenumcount");
                    if ("".equals(linenumcount)){
                        linenumcount = "20";
                    }
                    int num2 = Integer.parseInt(linenumcount);
                    //字每分钟  num1
                    timeting = num1 / num2;
//                    timeting = timeting *60;
                    timeting = 1000 *60 / timeting;
                    handlerdelay.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            int[] position = new int[2];
                            view_line_bg.getLocationInWindow(position);

                            Layout layout = tv_text.getLayout();
                            Rect bound = new Rect();
                            layout.getLineBounds(addcount, bound);//获取该行的Bound区域
                            int yAxisBottom = bound.bottom;//字符底部y坐标(相对于TextView的坐标)
                            int yAxisTop = bound.top;//字符顶部y坐标(相对于TextView的坐标)
                            MyLog.e("当前行再textview中的位置",yAxisBottom+"   "+yAxisTop);



                            if (position[1] > screenheight / 2) {

                                int i1 = lineHeight * addcount;
                                if (i1 > tv_text.getHeight()){
                                    handlerdelay.removeCallbacksAndMessages(null);
                                    img_start.setImageResource(R.mipmap.icon_start);
                                    img_start.setTag(0);
                                    return;
                                }

                                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();
//                                int i = lineHeight + position[1];
                                int i3 = lineHeight;
                                MyLog.e("跳转行高",i3+"    跳转行高");
                                if (islongscreen){
                                    i3 = lineHeight + 1;
                                }
                                MyLog.e("跳转行高+ 3",i3+"    跳转行高+ 3");
                                int i2 = i3 * addcount;
                                MyLog.e("11跳转行高+ 3*addcount",i2+"    跳转行高+ 3*addcount");
                                layoutParams.setMargins(0, i2, 0, 0);
                                view_line_bg.setLayoutParams(layoutParams);
                                addcount++;
                                scrollView.scrollBy(0, i3);
                                handlerdelay.postDelayed(this, timeting);


                                int topMargin = layoutParams.topMargin;
                                int top = view_line_bg.getTop();
                            } else {
                                int i1 = lineHeight * addcount;
                                if (i1 > tv_text.getHeight()){
                                    handlerdelay.removeCallbacksAndMessages(null);
                                    img_start.setImageResource(R.mipmap.icon_start);
                                    img_start.setTag(0);
                                    return;
                                }
                                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();
                                int i = lineHeight + position[1];
                                int i3 = lineHeight;
                                MyLog.e("跳转行高",i3+"    跳转行高");
                                if (islongscreen){
                                    i3 = lineHeight + 1;
                                }
                                MyLog.e("跳转行高+ 3",i3+"    跳转行高+ 3");
                                int i2 = i3 * addcount;
                                MyLog.e("11跳转行高+ 3*addcount",i2+"    跳转行高+ 3*addcount");
                                layoutParams.setMargins(0, i2, 0, 0);
                                view_line_bg.setLayoutParams(layoutParams);
                                addcount++;
                                handlerdelay.postDelayed(this, timeting);


                                int topMargin = layoutParams.topMargin;
                                int top = view_line_bg.getTop();
                            }
                        }
                    }, timeting);
                }else{
                    handlerdelay.removeCallbacksAndMessages(null);
                    img_start.setImageResource(R.mipmap.icon_start);
                    img_start.setTag(0);
                }

            }
        });
    }

    @Override
    protected int initLayout() {
        return R.layout.activity_freespeed2;
    }

    @Override
    protected void initView() {
        changeTitle("王冰寒");
//        saveNoticeList("name", "王冰寒");
        bookid = getIntent().getStringExtra("id");
        locationkey = "sudulocation"+bookid;
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        // 屏幕宽度（像素）
        screenwidth = metric.widthPixels;
        // 屏幕高度（像素）
        screenheight = metric.heightPixels;

        tv_set = findViewById(R.id.tv_set);
        tv_progress_tv = findViewById(R.id.tv_progress_tv);
        ll_rebackf = findViewById(R.id.ll_rebackf);
        scrollView = findViewById(R.id.scrollView);
        tv_titlebook = findViewById(R.id.tv_titlebook);
        tv_text = findViewById(R.id.tv_text);
        img_start = findViewById(R.id.img_start);
        img_start.setTag(0);
        view_line_bg = findViewById(R.id.view_line_bg);
        seek_progress = findViewById(R.id.seek_progress);
        seek_progress.setOnSeekBarChangeListener(mSeekBarListener);
        handlerdelay = new Handler();



        getData();


    }

    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);

        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();
        layoutParams.height = lineHeight;
        int topMargin = layoutParams.topMargin;
        view_line_bg.setLayoutParams(layoutParams);
        int top = view_line_bg.getTop();


        int[] position = new int[2];
        view_line_bg.getLocationInWindow(position);
        System.out.println("getLocationInWindow:" + position[0] + "," + position[1]);


    }

    @Override
    protected void initData() {

    }

    private void GetByHttpClient(final String url) {
        new Thread() {
            public void run() {
                try {

                    /**
                     * OkHttpClient 的Get请求
                     */
                    //创建okHttpClient对象
                    OkHttpClient mOkHttpClient;
                    mOkHttpClient = new OkHttpClient();
                    //创建一个Request
                    final Request request = new Request.Builder()
                            .url(url)
                            .build();
                    //new call
                    Call call = mOkHttpClient.newCall(request);
                    //请求加入调度
                    call.enqueue(new Callback() {
                        @Override
                        public void onFailure(Call call, IOException e) {

                        }

                        @Override
                        public void onResponse(Call call, Response response) throws IOException {

//                            String str = new String(new String(response.body().bytes(), "gb2312"));
//                            String htmlStr = str;
                            String htmlStr = response.body().string();
//                            MyLog.e("jorli=====>", htmlStr);
                            Message msg = new Message();
                            msg.arg1 = 10;
                            msg.obj = htmlStr;
                            if (handlerData != null) {
                                handlerData.sendMessage(msg);
                            }
                        }

                    });

                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            ;
        }.start();
    }


    private void getData() {
        String token = sharedPreferences.getString("token", "");
        String url = myapp.getWebConfig() + "/api/speed/detail";
        HashMap<String, String> paramsMap = new HashMap<>();
        paramsMap.put("id", bookid);
        paramsMap.put("token", token);
        MyLog.e("速读详情", bookid + "   ");
//        paramsMap.put("is_material", apptype);
        RequestManager.getInstance(context).requestAsyn(url, RequestManager.TYPE_POST_FORM, paramsMap, new RequestManager.ReqCallBack() {
            @Override
            public void onReqSuccess(Object result) {
                MyLog.e("code--result", result.toString());
                Message msg = new Message();
                try {
                    JSONObject jsonObject = new JSONObject(result.toString());
                    if (jsonObject.getString("code").equals("0")) {
                        msg.obj = jsonObject.getString("msg");
                        msg.arg1 = 0;
                        handlerData.sendMessage(msg);
                        return;
                    }
                    JSONObject data = jsonObject.getJSONObject("data");
                   /* "id": 12,
                            "name": "巴黎圣母院",
                            "image": "https://oss.bigchun.com/fastmemory/uploads/20200603/462eb8dbe419a521ea6887acca4e88cf.jpg",
                            "author": "维克多·雨果",
                            "minute_num": [
                    "约34万字"
        ],
                    "file": "https://oss.bigchun.com/fastmemory/uploads/20200603/991fa046c50fde940b59fcbc4fa3831a.txt",*/
                    id = data.getString("id");
                    bookname = data.getString("name");
                    bookauthor = data.getString("author");
                    file = data.getString("file");
                    minute_num = data.getJSONArray("minute_num");


                    msg.arg1 = 2;
                    handlerData.sendMessage(msg);
                } catch (JSONException e) {
                    e.printStackTrace();
                    msg.arg1 = 1;
                    handlerData.sendMessage(msg);
                }
            }

            @Override
            public void onReqFailed(String errorMsg) {
                if (errorMsg.equals("未登录")) {
                    Message msg = new Message();
                    msg.arg1 = 11;
                    handlerData.sendMessage(msg);
                } else {
                    Message msg = new Message();
                    msg.arg1 = 12;
                    handlerData.sendMessage(msg);
                }
            }
        });
    }

    /**
     * 进度拖动条监听器
     */
    private SeekBar.OnSeekBarChangeListener mSeekBarListener = new SeekBar.OnSeekBarChangeListener() {
        // 通知进度已经被修改
        public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
            if (fromUser) {
                changeprogress = progress;
            }
        }

        // 通知用户已经开始一个触摸拖动手势
        public void onStartTrackingTouch(SeekBar seekBar) {

            img_start.setImageResource(R.mipmap.icon_start);
            img_start.setTag(0);
            handlerdelay.removeCallbacksAndMessages(null);
        }

        // 通知用户触摸手势已经结束
        public void onStopTrackingTouch(SeekBar seekBar) {
            //最小300  最大5000    总长度是4700   每一个格子是47
            num1 = 47 * changeprogress;
            num1 = num1 +300;
            int jishu = num1 / 100;
            int startnum = jishu*100;
            int jishu2 = jishu+1;
            int endnum = jishu2*100;
            tv_progress_tv.setText(startnum+"~"+endnum+"字/分钟");


        }
    };

    /**
     * 弹出搜索框
     */
    private void popbysettime() {

       // 1~100   20



        LayoutInflater layoutInflater = LayoutInflater.from(context);
        View popupWindow = layoutInflater.inflate(R.layout.popup_set_zi, null);

        RegionNumberEditText  et_zishu = popupWindow.findViewById(R.id.et_zishu);
        TextView tv_cancle = popupWindow.findViewById(R.id.tv_cancle);
        TextView tv_sure = popupWindow.findViewById(R.id.tv_sure);
        et_zishu.setRegion(100,1);
        et_zishu.setTextWatcher();

        tv_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                mPopupWindowtime.dismiss();
            }
        });
        tv_sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String trim = et_zishu.getText().toString().trim();
                if ("".equals(trim)){
                    ToastUtils.show("请输入需要设置的字号");
                }else{
                    savelable();
                    saveUserInfo("sudusize",trim);
                    int tvsize = Integer.parseInt(trim);
                    isfirst = true;
                    tv_text.setTextSize(tvsize);
                    lineHeight = tv_text.getLineHeight();
                    view_line_bg.setVisibility(View.VISIBLE);
                    float lineSpacingExtra = tv_text.getLineSpacingExtra();
                    float asdsa = tv_text.getLineSpacingMultiplier();
                    if (lineSpacingExtra > 2){
                        islongscreen = true;
                        int v = (int) (lineSpacingExtra - 2);
                        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();
                        lineHeight = lineHeight+v;
                        layoutParams.height = lineHeight+v;
                        view_line_bg.setLayoutParams(layoutParams);
                    }else{
                        islongscreen = false;
                        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();
                        layoutParams.height = lineHeight;
                        view_line_bg.setLayoutParams(layoutParams);
                    }

                    int sudulocation = Integer.parseInt(getUserInfo(locationkey));
                    Layout layout = tv_text.getLayout();
//                    float width = layout.getLineWidth((int)addcount-1); //指定行的宽度
                    String text = tv_text.getText().toString();
                    int end;
                    int start = 0;
                    for (int i = 0; i < tv_text.getLineCount(); i++) {
                        end = layout.getLineEnd(i);

                        String linecontent = text.substring(start, end); //指定行的内容
                        if (sudulocation>=start&&sudulocation <=end){
                            isfirst = true;

                            saveUserInfo(locationkey,start+"");
                            initLoca();
                            break;
                        }
                        start = end;
                        float widthnew = layout.getLineWidth(i); //指定行的宽度

                    }

                    mPopupWindowtime.dismiss();

                }
            }
        });

        mPopupWindowtime = new PopupWindow(popupWindow, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT);
        int mPopupWindowWidth = mPopupWindowtime.getWidth();
        int mPopupWindowHeight = mPopupWindowtime.getHeight();
        // 需要设置一下此参数，点击外边可消失
        mPopupWindowtime.setBackgroundDrawable(new BitmapDrawable());
        mPopupWindowtime.setOutsideTouchable(true);
        mPopupWindowtime.setTouchable(true);
        mPopupWindowtime.setFocusable(true); // pop 显示时， 不让外部 view 响应点击事件
        //防止被底部虚拟键挡住
        mPopupWindowtime.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        if (Build.VERSION.SDK_INT >= 24) { // Android 7.x中,PopupWindow高度为match_parent时,会出现兼容性问题,需要处理兼容性
            int Screenheightth = getWindowManager().getDefaultDisplay().getHeight();
            mPopupWindowtime.showAtLocation(tv_set,
                    Gravity.BOTTOM,
                    0,
                    Screenheightth / 2);
//            Log.e("底部导航栏高度", utils.getNavigationBarHeight(context) + "    gaodu");

        } else {
            int Screenheightth = getWindowManager().getDefaultDisplay().getHeight();
            mPopupWindowtime.showAtLocation(tv_set,
                    Gravity.BOTTOM,
                    0,
                    0);
        }
        mPopupWindowtime.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        handlerdelay.removeCallbacksAndMessages(null);
    }

    public Handler handlerData = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.arg1) {
                case 0:
                    String obj = (String) msg.obj;
                    ToastUtils.show(obj);
                    break;
                case 1:
                    ToastUtils.show(R.string.net_error);
                    break;
                case 2:
                    String num = "";
                    if (minute_num.length() > 0){
                        try {
                            num = minute_num.getString(0);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    String title = bookname+num+" 作者："+bookauthor;
                    SpannableString spanString = new SpannableString(title);
                    //再构造一个改变字体颜色的Span
                    ForegroundColorSpan span = new ForegroundColorSpan(Color.BLACK);
                    //将这个Span应用于指定范围的字体    前包括后不包括
                    spanString.setSpan(span, 0, bookname.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                    AbsoluteSizeSpan spansize = new AbsoluteSizeSpan(36);
                    spanString.setSpan(spansize, 0, bookname.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                    tv_titlebook.setText(spanString);
                    /*tv_titlebook.setText(title);
                    tv_titlebook.setFocusable(true);*/
                    GetByHttpClient(file);


                    break;
                case 3:
                    break;
                case 4:


                    break;
                case 5:

                    break;
                case 6:

                    break;
                case 7:

                    break;
                case 8:


                    break;
                case 9:

                    break;
                case 10:
                    String sudusize = getUserInfo("sudusize");
                    if (!"".equals(sudusize)){
                        int ssize = Integer.parseInt(sudusize);
                        tv_text.setTextSize(ssize);
                    }
                    contentobj = (String) msg.obj;
                    contentlength = contentobj.length();
                    tv_text.setText(contentobj);
                    lineHeight = tv_text.getLineHeight();
                    MyLog.e("初始值行高",lineHeight+"   初始值行高");


                    view_line_bg.setVisibility(View.VISIBLE);
                    if (customProgressDialog != null){
                        if (customProgressDialog.isShowing()){
                            customProgressDialog.dismiss();
                        }
                    }
                    float lineSpacingExtra = tv_text.getLineSpacingExtra();
                    float lineMultiplier = tv_text.getLineSpacingMultiplier();
                    MyLog.e("行距和倍数",lineSpacingExtra+"    "+lineMultiplier);

                    float asdsa = tv_text.getLineSpacingMultiplier();
                    if (lineSpacingExtra > 2){
                        islongscreen = true;
                        int v = (int) (lineSpacingExtra - 2);
                        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();

                        lineHeight = lineHeight+v;
                        MyLog.e("初始值行高+行距",lineHeight+"   初始值行高+行距");
                        layoutParams.height = lineHeight;
                        view_line_bg.setLayoutParams(layoutParams);
                    }else{
                        islongscreen = false;
                        RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();
                        layoutParams.height = lineHeight;
                        view_line_bg.setLayoutParams(layoutParams);
                    }
                    String linenumcount = getUserInfo("linenumcount");
                    if ("".equals(linenumcount) || linenumcount == null){
//                        popbysettime();
                    }
                    initLoca();
                    break;
                case 11:
                    sharedPreferences.edit().putString("user_id","").commit();
                    sharedPreferences.edit().putString("username","").commit();
                    sharedPreferences.edit().putString("nickname","").commit();
                    sharedPreferences.edit().putString("mobile","").commit();
                    sharedPreferences.edit().putString("avatar","").commit();
                    sharedPreferences.edit().putString("score","").commit();
                    sharedPreferences.edit().putString("student_id","").commit();
                    sharedPreferences.edit().putString("is_bind_wx","").commit();
                    sharedPreferences.edit().putString("token","").commit();
                    sharedPreferences.edit().putString("is_agent","").commit();
                    sharedPreferences.edit().putString("vip_expire","").commit();
                    sharedPreferences.edit().putString("is_vip","").commit();
                    finish();
                    break;
                case 13:

                    break;

            }

        }
    };

    /**
     * 弹出搜索框收藏
     */
    private void popbygrade(View viewlayout) {

        LayoutInflater layoutInflater = LayoutInflater.from(context);
        View popupWindow = layoutInflater.inflate(R.layout.layout_pop_sudu, null);
        LinearLayout ll_pop_setsize = popupWindow.findViewById(R.id.ll_pop_setsize);
        LinearLayout ll_pop_saveshuqian = popupWindow.findViewById(R.id.ll_pop_saveshuqian);
        ll_pop_setsize.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mPopupResultWindow != null) {
                    if (mPopupResultWindow.isShowing()) {
                        mPopupResultWindow.dismiss();
                    }
                }
                if (DensityUtil.isFastDoubleClick()){
                    return;
                }
                popbysettime();
            }
        });
        ll_pop_saveshuqian.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (mPopupResultWindow != null) {
                    if (mPopupResultWindow.isShowing()) {
                        mPopupResultWindow.dismiss();
                    }
                }
                savelable();
            }
        });

        mPopupResultWindow = new PopupWindow(popupWindow, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.MATCH_PARENT);
        int mPopupWindowWidth = mPopupResultWindow.getWidth();
        int mPopupWindowHeight = mPopupResultWindow.getHeight();
        // 需要设置一下此参数，点击外边可消失
        mPopupResultWindow.setBackgroundDrawable(new BitmapDrawable());
        mPopupResultWindow.setOutsideTouchable(true);
        mPopupResultWindow.setTouchable(true);
        mPopupResultWindow.setFocusable(true); // pop 显示时， 不让外部 view 响应点击事件
        //防止被底部虚拟键挡住
        mPopupResultWindow.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE);
        if (Build.VERSION.SDK_INT >= 24) { // Android 7.x中,PopupWindow高度为match_parent时,会出现兼容性问题,需要处理兼容性
            int Screenheightth = getWindowManager().getDefaultDisplay().getHeight();
//            mPopupResultWindow.showAtLocation(ll_more_end,
//                    Gravity.BOTTOM,
//                    0,
//                    Screenheightth / 2);
            mPopupResultWindow.showAsDropDown(viewlayout, -100, 0);
//            Log.e("底部导航栏高度", utils.getNavigationBarHeight(context) + "    gaodu");

        } else {
            int Screenheightth = getWindowManager().getDefaultDisplay().getHeight();
//            mPopupResultWindow.showAtLocation(ll_more_end,
//                    Gravity.BOTTOM,
//                    0,
//                    0);
            mPopupResultWindow.showAsDropDown(viewlayout, -100, 0);
        }
        mPopupResultWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {

            }
        });

    }

    public void savelable(){
        Layout layout = tv_text.getLayout();
        float width = layout.getLineWidth(addcount); //指定行的宽度
        int end;
        int start = 0;
        start = layout.getLineEnd(addcount-1);
        end = layout.getLineEnd(addcount);
        String text = tv_text.getText().toString();
        String line = text.substring(start, end); //指定行的内容


        saveUserInfo(locationkey,start+"");

    }

    boolean isfirst = true;
    public void initLoca(){
        tv_text.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @Override

            public void onGlobalLayout() {
                if (isfirst){
                    isfirst = false;
                    String sudulocation1 = getUserInfo(locationkey);
                    int sudulocation =0;
                    if (!"".equals(sudulocation1)){
                        sudulocation = Integer.parseInt(sudulocation1);
                    }
                    if (!"".equals(sudulocation)){
                        Layout layout = tv_text.getLayout();
                        String text = tv_text.getText().toString();
                        int end;
                        int start = 0;
                        for (int i = 0; i < tv_text.getLineCount(); i++) {
                            end = layout.getLineEnd(i);

                            String linecontent = text.substring(start, end); //指定行的内容
                            if (sudulocation>=start&&sudulocation <=end){
                                addcount = i;
                                break;
                            }
                            start = end;
                            float widthnew = layout.getLineWidth(i); //指定行的宽度

                        }
                        int[] position = new int[2];
                        view_line_bg.getLocationInWindow(position);
                        if (position[1] > screenheight / 2) {

                            int i1 = lineHeight * addcount;
                            if (i1 > tv_text.getHeight()){
                                handlerdelay.removeCallbacksAndMessages(null);
                                img_start.setImageResource(R.mipmap.icon_start);
                                img_start.setTag(0);
                                return;
                            }

                            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();
                            int i = lineHeight + position[1];
                            int i3 = lineHeight;
                            MyLog.e("初始值行高+加载完成",lineHeight+"   初始值行高+加载完成");
                            if (islongscreen){
                                i3 = lineHeight + 1;
                                MyLog.e("初始值行高+加载完成+3",lineHeight+"   初始值行高+加载完成+3");
                            }
                            int i2 = i3 * addcount;
                            MyLog.e("view据顶部margin",lineHeight+"   view据顶部margin");
                            layoutParams.setMargins(0, i2, 0, 0);
                            view_line_bg.setLayoutParams(layoutParams);
                            scrollView.scrollBy(0, i3);


                            int topMargin = layoutParams.topMargin;
                            int top = view_line_bg.getTop();
                            scrollView.scrollTo(0,topMargin);
                        } else {
                            int i1 = lineHeight * addcount;
                            if (i1 > tv_text.getHeight()){
                                handlerdelay.removeCallbacksAndMessages(null);
                                img_start.setImageResource(R.mipmap.icon_start);
                                img_start.setTag(0);
                                return;
                            }
                            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) view_line_bg.getLayoutParams();
                            int i = lineHeight + position[1];
                            int i3 = lineHeight;
                            MyLog.e("初始值行高+加载完成",lineHeight+"   初始值行高+加载完成");
                            if (islongscreen){
                                i3 = lineHeight + 1;
                                MyLog.e("初始值行高+加载完成+3",lineHeight+"   初始值行高+加载完成+3");
                            }
                            int i2 = i3 * addcount;
                            MyLog.e("view据顶部margin",lineHeight+"   view据顶部margin");
                            layoutParams.setMargins(0, i2, 0, 0);
                            view_line_bg.setLayoutParams(layoutParams);
                            int topMargin = layoutParams.topMargin;
                            int top = view_line_bg.getTop();
                            scrollView.scrollTo(0,topMargin);
                        }
                    }
                }
                }


        });




    }

}
